package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapSort;
import com.ruoyi.system.outto.core.constant.GameTypeConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.JYYAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author lz
 * @version 1.0
 * @date 2022/8/16 22:58
 */
@Slf4j
@Service
public class JYYApiImpl implements JYYAPI {

    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private AccountInfoMapper accountInfoMapper;

    /**
     * @param accountInfo
     * @param userId
     * @param operation   //(1,添加) (2,修改)(3,上下架)
     * @param isdel       是不是删除
     * @param salePartner
     * @return
     */
    @Override
    public AjaxResult addAndEditAndDelGame(AccountInfo accountInfo, Long userId, Integer operation, boolean isdel, SalePartner sa) {
        Map<String, Object> resultMap = new HashMap<>();
        String url = sa.getThreeOther();
        Map<String, Object> params = params(accountInfo, sa);

        params.put("operation", operation);
        //（0，显示）（2，已下架）
        params.put("showSign", isdel ? 2 : 0);
        params = doneCommonParms(sa, params);
        String requestp = JSONObject.toJSONString(params);
        log.info("交易游{}( //(1,添加) (2,修改)(3,上下架))接口请求参数={}", operation, requestp);
        String result = null;
        JSONObject json = JSONObject.parseObject(requestp);
        try {
            result = HttpUtils.doPostForm(url, params, null);
        } catch (Exception e) {
            return getAjaxResult(resultMap, requestp, result);
        }
        log.info("交易游{}( //(1,添加) (2,修改)(3,上下架))接口返回参数={}", operation, result);

        return getAjaxResult(resultMap, requestp, result);
    }

    private SalePartner getSalePartner(Long userId) {
        SalePartner sa = commonApi.get(LCConstant.saleNameJYY, userId);
        if (Objects.isNull(sa)) {
            throw new GlobalException("合作伙伴未查到");
        }
        return sa;
    }


    private Map<String, Object> params(AccountInfo accountInfo, SalePartner sa) {
        Map<String, Object> params = new TreeMap<>();
        String gameType = accountInfo.getType();
        String title = accountInfo.getDes();
        Long id = accountInfo.getId();
        String titleImg = accountInfo.getTitleImg();
        Integer gameId = getGameId(gameType);
        if (gameId == null) {
            log.error("游戏未找到{}", gameType);
            throw new GlobalException("游戏未找到" + gameId);
        }
        Integer regionalCover = regionalCover(accountInfo.getType(), accountInfo.getRegional());
        if (Objects.isNull(regionalCover)) {
            throw new GlobalException("区服匹配失败，当前游戏:" + gameType + "，区服" + accountInfo.getRegional());
        }
        params.put("areaId", regionalCover);
        params.put("gameId", gameId);
        params.put("goodsTypeId", 1);
        params.put("goodsNum", 1);
        params.put("bigTitle", "【" + descTitle + "_" + accountInfo.getId() + "】 " + title);
        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(),sa);
        params.put("price", String.valueOf(bigDecimal));
        params.put("goodsDecs", accountInfo.getDes());
        params.put("thumbnail", StringUtils.isEmpty(titleImg) ? "https://game.ikbh.top/logo/no_img.jpg" : titleImg);
        //图片
        StringBuilder imagesSb = new StringBuilder();
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(id);
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if (CollectionUtils.isEmpty(infoImgs)) {
        } else {
            for (InfoImg img : infoImgs) {
                imagesSb.append(img.getImgUrl()).append(",");
            }
        }
        params.put("goodsImages", StringUtils.isEmpty(imagesSb.toString()) ? "https://game.ikbh.top/logo/no_img.jpg" : imagesSb.toString());
        params.put("outSn", String.valueOf(id));
        Integer serverId = getServerId(accountInfo.getType(), accountInfo.getRegional());
        params.put("serverId", serverId);
        return params;
    }


    private Integer regionalCover(String game, String regional) {
        if (game.equals(GameTypeConstant.WZRY)) {
            if (Objects.equals("安卓Q", regional)) {
                return 108;
            } else if (Objects.equals("安卓WX", regional)) {
                return 107;
            } else if (Objects.equals("苹果WX", regional)) {
                return 106;
            } else if (Objects.equals("苹果Q", regional)) {
                return 109;
            } else {
                return null;
            }
        }
        if (game.equals(GameTypeConstant.HPJY)) {
            if (Objects.equals("安卓Q", regional)) {
                return 185;
            } else if (Objects.equals("安卓WX", regional)) {
                return 185;
            } else if (Objects.equals("苹果WX", regional)) {
                return 184;
            } else if (Objects.equals("苹果Q", regional)) {
                return 184;
            } else {
                return null;
            }
        }
        if (game.equals(GameTypeConstant.YS)) {
            //"官服-天空岛服"
            return 282;
        }
        if (game.equals(GameTypeConstant.YJWJ)) {
            //steam
            return 374;
        }
        return null;
    }

    private Integer getServerId(String game, String regional) {
        if (game.equals(GameTypeConstant.WZRY)) {
            if (Objects.equals("安卓Q", regional)) {
                return 2388;
            } else if (Objects.equals("安卓WX", regional)) {
                return 2088;
            } else if (Objects.equals("苹果WX", regional)) {
                return 1788;
            } else if (Objects.equals("苹果Q", regional)) {
                return 2688;
            } else {
                return null;
            }
        }
        if (game.equals(GameTypeConstant.HPJY)) {
            if (Objects.equals("安卓Q", regional)) {
                return 8052;
            } else if (Objects.equals("安卓WX", regional)) {
                return 8051;
            } else if (Objects.equals("苹果WX", regional)) {
                return 8049;
            } else if (Objects.equals("苹果Q", regional)) {
                return 8050;
            } else {
                return null;
            }
        }
        if (game.equals(GameTypeConstant.YS)) {
            return 8102;
        }
        if (game.equals(GameTypeConstant.YJWJ)) {
            //全区全服
            return 8716;
        }
        return null;
    }

    private Integer getGameId(String game) {
        if (game.equals(GameTypeConstant.WZRY)) {
            return 3;

        } else if (game.equals(GameTypeConstant.HPJY)) {
            return 56;

//        } else if (game.equals(GameTypeConstant.CF)) {
//            return 5;
//
        } else if (game.equals(GameTypeConstant.LOL)) {
            return 4;

        } else if (game.equals(GameTypeConstant.YS)) {
            return 69;

        } else if (game.equals(GameTypeConstant.YJWJ)) {
            return 86;
        }
        return null;
    }

    /**
     * 公共参数
     *
     * @param sa
     */
    private Map<String, Object> doneCommonParms(SalePartner sa, Map<String, Object> params) {
        params.put("apiSuffix", sa.getSaleKey());
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        String key = sa.getOther();
        StringBuilder sb = new StringBuilder();
        HashMap<String, Object> newMap = new HashMap<>();

        for (final Map.Entry<String, Object> m : entries) {
            if (m.getValue() == null) {
                sb.append(m.getKey() + "=" + "1" + "&");
                newMap.put(m.getKey(), "1");
            } else {
                if (StringUtils.isEmpty(m.getValue().toString())) {
                    sb.append(m.getKey() + "=" + "1" + "&");
                    newMap.put(m.getKey(), "1");

                } else {
                    sb.append(m.getKey() + "=" + m.getValue().toString() + "&");
                    newMap.put(m.getKey(), m.getValue());
                }
            }

        }
//        String substring = sb.substring(0, sb.length() - 1);
        newMap.put("sign", DigestUtils.md5Hex(sb + "key=" + key));
        return newMap;
    }

    private static AjaxResult getAjaxResult(Map<String, Object> resultMap, String requestp, String result) {
        JSONObject resultJson = JSONObject.parseObject(result);
        if (resultJson != null) {
            if (!"0".equals(resultJson.getString("code"))) {
                resultMap.put("code", 500);
            } else {
                resultMap.put("code", 200);
            }
            resultMap.put("msg", resultJson.toJSONString());
        } else {
            resultMap.put("code", 500);
            resultMap.put("msg", "未知");
        }

        resultMap.put("req", requestp);
        resultMap.put("res", result);
        return AjaxResult.success(resultMap);
    }

}
